<template>
  <div>
    <span class="avar">
      <el-upload
        ref="avatar"
        class="avatar-uploader"
        action="http://47.93.200.120:433/Api/FileUploadApi.ashx"
        :show-file-list="false"
        :before-upload="beforeAvatarUpload"
        style="position: absolute;z-index: 999;"
      >
        <img v-if="image" :src="image" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon" />
      </el-upload>
    </span>
  </div>
</template>

<script>
export default {
  components: {},

  props: {
    fieldName: { type: String, default: undefined },
    image: { type: String, default: undefined }
  },
  data() {
    return {
      imageUrl: ''
    }
  },

  computed: {},

  async created() {},
  mounted() {},
  methods: {
    getBase64(file) {
      return new Promise(function(resolve, reject) {
        const reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function() {
          imgResult = reader.result
        }
        reader.onerror = function(error) {
          reject(error)
        }
        reader.onloadend = function() {
          resolve(imgResult)
        }
      })
    },

    beforeAvatarUpload(file) {
      this.getBase64(file).then(res => {
        // console.log(res);
        // this.imageUrl = res

        this.$emit('onloadend', { value: res, field: this.fieldName })
      })

      return false
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 70px;
  height: 70px;
  line-height: 70px;
  text-align: center;
}
.avatar {
  width: 70px;
  height: 70px;
  display: block;
}
</style>
